package cn.client.ui.view.main.user

import android.app.Activity
import android.content.Intent
import android.net.Uri
import android.util.Log
import android.widget.Toast
import androidx.activity.compose.rememberLauncherForActivityResult
import androidx.activity.result.contract.ActivityResultContracts
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.material.ExperimentalMaterialApi
import androidx.compose.material.ListItem
import androidx.compose.material.ModalBottomSheetLayout
import androidx.compose.material.ModalBottomSheetState
import androidx.compose.material.ModalBottomSheetValue
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.MoreVert
import androidx.compose.material.icons.filled.Output
import androidx.compose.material.rememberModalBottomSheetState
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Tab
import androidx.compose.material3.TabRow
import androidx.compose.material3.Text
import androidx.compose.material3.TopAppBar
import androidx.compose.material3.TopAppBarDefaults
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.MutableState
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.runtime.setValue
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.unit.dp
import androidx.hilt.navigation.compose.hiltViewModel
import androidx.navigation.NavController
import cn.client.R
import cn.client.data.userStateManager
import cn.client.ui.components.ThisUserInfoCard
import cn.client.ui.view.main.user.avoidancePain.AvoidancePainContent
import cn.client.ui.view.main.user.emotionLog.EmotionLogContent
import cn.client.utlis.uriToFileApiQ
import kotlinx.coroutines.launch


/**
 * 用户页面
 */
@OptIn(ExperimentalMaterialApi::class)
@Composable
fun UserInfo(
    onClickEditUserInfo: (Int) -> Unit = {},
    onClickSignOut: () -> Unit = {},
    navController: NavController,
    viewModel: UserInfoViewModel = hiltViewModel()
) {

    // 监听状态
    val sheetState = rememberModalBottomSheetState(initialValue = ModalBottomSheetValue.Hidden)
    val coroutineScope = rememberCoroutineScope()
    var selectedUri: Uri? by mutableStateOf(null)

    val context = LocalContext.current
    // 观察ViewModel中的状态
    val states = viewModel.pageStates

    // 使用 collectAsState 观察 userId 的变化
//    val userIdState = viewModel.userId.collectAsState(initial = -1)
//    val userId = userIdState.value
    val userIdState = userStateManager.userId.collectAsState(initial = -1)
    val userId = userIdState.value

    val selectedTabIndex = mutableStateOf(0)


    if (userId == -1) {
        viewModel.dispatch(UserInfoViewModel.PageIntent.GetUser("获取本地用户缓存"))
    } else if (userId != -1 ) {
        viewModel.dispatch(UserInfoViewModel.PageIntent.GetUserInfo(userId))
    }

    //  使用LaunchedEffect来启动协程，收集事件
    LaunchedEffect(Unit) {
        viewModel.pageEvents.collect { it ->
            when (it) {
                is UserInfoViewModel.PageEvent.Out -> {
                    Toast.makeText(context, "提示：${it.res}", Toast.LENGTH_SHORT).show()
                    onClickSignOut()
                }
                is UserInfoViewModel.PageEvent.UserRes -> {
                    viewModel.dispatch(UserInfoViewModel.PageIntent.GetUserInfo(userId))
                }
                is UserInfoViewModel.PageEvent.Error -> {
                    Toast.makeText(context, "提示：${it.error}", Toast.LENGTH_SHORT).show()
                }
                else -> {
                    Unit
                }
            }
        }
    }
    // 修改头像
    val avatarLauncher = rememberLauncherForActivityResult(
        contract = ActivityResultContracts.StartActivityForResult()
    ) { result ->
        if (result.resultCode == Activity.RESULT_OK) {
            val data: Intent? = result.data
            data?.data?.let { uri ->
                selectedUri = uri
                val file = uriToFileApiQ(selectedUri, context)
                Log.d("onFileSelected","处理文件")
                viewModel.dispatch(
                    UserInfoViewModel.PageIntent.UpAvatar(
                        uid = userId,
                        file = file!!
                    )
                )
            }
        }
    }

    // 底部弹窗
    UserInfoBottomSheetLayout(
        onClickEditUserAvatar = {
            val intent = Intent(Intent.ACTION_GET_CONTENT)
            intent.type = "image/*"
            avatarLauncher.launch(intent)
        },
        onClickEditUserInfo = {
            coroutineScope.launch {
                onClickEditUserInfo(userId)
            }
        },
        onClickOutput = {

        },
        sheetState = sheetState
    ) {
        Column(
            modifier = Modifier
                .fillMaxSize()
                .background(Color.White)
        ) {
            /* 顶部导航栏 */
            UserInfoTopBar(
                onClickUserInfoTopBar = {
                    /* 底部弹窗 */
                    coroutineScope.launch {
                        sheetState.show()
                    }
                }
            )
            /* 用户card */
            ThisUserInfoCard(
                avatarURL = states.avatar,
                backGroundURL = states.background,
                userName = states.uname,
                email = states.email,
                birthday = states.birthday,
                area = states.area
            )
            /* 内容区域 */
            UserInfoTabContent(navController = navController, selectedTabIndex = selectedTabIndex)
        }
    }


}


@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun UserInfoTopBar(
    onClickUserInfoTopBar : () -> Unit
) {
    TopAppBar(
        colors = TopAppBarDefaults.topAppBarColors(
            containerColor = MaterialTheme.colorScheme.primaryContainer,
            titleContentColor = MaterialTheme.colorScheme.primary
        ),
        title = { Text("个人信息") },
        /* 左边按钮 */
        navigationIcon = {
//            Icon( painter = painterResource(R.drawable.ic_share_one), null)
            Spacer(modifier = Modifier.size(24.dp))
        },
        /* 右边按钮（可以是多个） */
        actions = {
            IconButton(onClick = {
                onClickUserInfoTopBar()
            }
            ) {
                Icon(Icons.Filled.MoreVert, null)
            }
        }
    )
}



@Composable
fun UserInfoTabContent(
    navController: NavController,
    selectedTabIndex: MutableState<Int>
){
    TabRow(
        selectedTabIndex = selectedTabIndex.value,
        modifier = Modifier.fillMaxWidth()
    ) {
        /* tab1 */
        Tab(
            selected = selectedTabIndex.value == 0,
            onClick = { selectedTabIndex.value = 0 },
            text = { Text(text = "痛苦回避列表") }
        )
        /* tab2 */
        Tab(
            selected = selectedTabIndex.value == 1,
            onClick = { selectedTabIndex.value = 1 },
            text = { Text(text = "情绪日志") }
        )
    }
    UserInfoContent(navController = navController,index = selectedTabIndex.value)
}

@Composable
fun UserInfoContent(
    navController: NavController,
    index: Int
){
    when (index) {
        0 -> {
            // Tab 1 的内容
            AvoidancePainContent(navController)
        }
        1 -> {
            // Tab 2 的内容
            EmotionLogContent(navController)
        }
    }

}


@OptIn(ExperimentalMaterialApi::class)
@Composable
fun UserInfoBottomSheetLayout(
    onClickEditUserInfo: () -> Unit = {},
    onClickEditUserAvatar: () -> Unit = {},
    onClickOutput: () -> Unit = {},
    sheetState: ModalBottomSheetState,
    content: @Composable () -> Unit
) {
    val coroutineScope = rememberCoroutineScope()
    ModalBottomSheetLayout(
        sheetState = sheetState,
        sheetContent = {
            Column {
                //这里显示底部弹窗内容
                ListItem(
                    text = { Text("修改信息") },
                    icon = {
                        Icon(
                            painterResource(R.drawable.ic_edit_user),
                            null,
                            tint = Color.DarkGray,
                            modifier = Modifier.padding(4.dp)
                        )
                    },
                    modifier = Modifier.clickable {
                        coroutineScope.launch {
                            onClickEditUserInfo() // 直接调用传递进来的函数
                        }
                    }
                )
                ListItem(
                    text = { Text("修改头像") },
                    icon = {
                        Icon(
                            painterResource(R.drawable.ic_edit_user),
                            null,
                            tint = Color.DarkGray,
                            modifier = Modifier.padding(4.dp)
                        )
                    },
                    modifier = Modifier.clickable {
                        coroutineScope.launch {
                            onClickEditUserAvatar() // 直接调用传递进来的函数
                        }
                    }
                )
                ListItem(
                    text = { Text("退出登录") },
                    icon = {
                        Icon(
                            Icons.Filled.Output,
                            null,
                            tint = Color.DarkGray,
                            modifier = Modifier.padding(4.dp)
                        )
                    },
                    modifier = Modifier.clickable {
                        coroutineScope.launch {
                            onClickOutput() // 直接调用传递进来的函数
                        }
                    }
                )
                // 占位符
                Spacer(
                    modifier = Modifier
                        .height(80.dp)
                        .fillMaxWidth()
                )
            }
        }) {
        content()
    }
}


